/* 整个界面都需要消息通讯imData*/
// import { mergeArray } from '@/tim';

const initState = {
  userId_: '', // 用户id
  currentUser: {},
  supplierId: '', // 直播的群主id
  isSdkReady: false, // imskd初始化status
  currentProfile: {}, // 目前登陆的账号信息
  conversationList: [], // 会话列表
  currentConversation: {}, // 目前的会话对象
  currentMessageList: [],
  nextReqMessageID: '', // 无限滚动处理 最开始的消息id
  isCompleted: false, // 还有没有消息
  liveRoomGroup: {}, // 直播互动群
  systemGroup: {},
}
export default {
  namespaced: true,
  state: initState,
  mutations: {
    set_systemGroup (state, systemGroup) {
      state.systemGroup = systemGroup
    },
    set_systemMessageList (state, systemMessageList) {
      state.systemMessageList = systemMessageList
    },
    set_currentUser (state, currentUser) {
      state.currentUser = currentUser
    },
    set_currentConversation (state, currentConversation) {
      state.isCompleted = false
      state.nextReqMessageID = ''
      state.currentConversation = currentConversation
    },
    set_default_conversation (state) {
      if (state.currentConversation && state.currentConversation.conversationID) {
        return false
      }
      state.currentConversation = state.conversationList && state.conversationList[0]
    },
    set_userId (state, userId_) {
      state.userId_ = userId_
    },
    set_supplierId (state, supplierId) {
      state.supplierId = supplierId
    },
    set_liveRoomGroup (state, liveRoomGroup) {
      state.liveRoomGroup = liveRoomGroup
      return liveRoomGroup
    },
    set_isSdkReady (state, isSdkReady) {
      state.isSdkReady = isSdkReady
    },
    updateCurrentProfile (state, currentProfile) {
      state.currentProfile = currentProfile
    },
    set_conversationList (state, conversationList) {
      state.conversationList = conversationList
    },
    /**
     * 更新会话列表
     * 调用时机：触发会话列表更新事件时。CONVERSATION_LIST_UPDATED
     * @param {Object} state
     * @param {Conversation[]} conversationList
     */
    updateConversationList (state, conversationList) {
      state.conversationList = conversationList
    },
    checkoutConversation (state, currentConversation) {
      state.currentConversation = currentConversation
    },
    set_currentMessageList (state, currentMessageList) {
      state.currentMessageList = currentMessageList
    },
    set_nextReqMessageID_null (state) {
      state.isCompleted = false
      state.nextReqMessageID = ''
    },
    pushCurrentMessageList (state, data) {
      // 还没当前会话，则跳过
      if (!state.currentConversation.conversationID) {
        return
      }
      if (Array.isArray(data)) {
        // 筛选出当前会话的消息
        const result = data.filter(item => item.conversationID === state.currentConversation.conversationID)
        state.currentMessageList = [...state.currentMessageList, ...result]
      } else if (data.conversationID === state.currentConversation.conversationID) {
        state.currentMessageList = [...state.currentMessageList, data]
      }
    }

  },
  getters: {
    systemGroupConversation (state) {
      var systemGroupConversationId_ = state.conversationList.filter(item => {
        return item && item.type == 'GROUP' && item.groupProfile && item.groupProfile.groupID == state.systemGroup && state.systemGroup.groupID
      })
      return systemGroupConversationId_ && systemGroupConversationId_[0]
    },
    totalUnreadCount (state) {
      var unreadCount = 0
      state &&
      state.conversationList &&
      state.conversationList.map(item => {
        if (item.type != 'GROUP' && item.type != '@TIM#SYSTEM' &&
          item.conversationID.indexOf(`GROUPgroup_zhibo`) > 0 &&
          item.conversationID.indexOf(`@TIM#SYSTEM`) > 0 &&
          item.conversationID.indexOf(`GROUPsystem_8f5ee644`) > 0
        ) {
          unreadCount += item.unreadCount
        }
      })
      return unreadCount
    },
  },
  actions: {
    /**
     * 加载消息列表
     * @param {Object} conversation  会话对象
     */
    loadMoreStore ({ state, commit }, conversation) {
      const { nextReqMessageID, currentMessageList } = state
      /* if (state.isCompleted) {
         console.log("消息列表已经读完不需要在加载 ")
         return false
       } //没有跟多消息了*/
      // if (!conversation) return false

      return window.tim.getConversationProfile(conversation.conversationID).then(({ data }) => {
        commit('checkoutConversation', data.conversation)
        console.log('目前conversation ', data.conversation, data.conversation.conversationID)
        return window.tim.getMessageList({
          conversationID: conversation && conversation.conversationID,
          nextReqMessageID,
          count: 15
        }).then(imReponse => {
          console.log('消息列表调成功 ', imReponse)
          state.nextReqMessageID = imReponse.data.nextReqMessageID
          state.isCompleted = imReponse.data.isCompleted
          // 更新当前消息列表，从头部插入
          // state.currentMessageList = mergeArray(currentMessageList, imReponse.data.messageList, 'ID')
          // 加载的新消息在后面
          state.currentMessageList = [...imReponse.data.messageList, ...currentMessageList]
          commit('set_currentMessageList', state.currentMessageList)
        }).catch(e => {
          console.error('   window._vm.tim.getMessageList({', e)
        })
      })
      // 跟新会话  获取聊天消息
    },
    /**
     * 获取消息列表
     * @param {Object} conversation  会话对象
     */
    getMessageList ({ state, commit }, conversation) {
      const { nextReqMessageID, currentMessageList } = state
      if (state.isCompleted) {
        return false
      } // 没有跟多消息了
      if (!conversation) return false
      window.tim.getMessageList({
        conversationID: conversation && conversation.conversationID,
        nextReqMessageID,
        count: 15
      })
        .then(imReponse => {
          state.nextReqMessageID = imReponse.data.nextReqMessageID
          state.isCompleted = imReponse.data.isCompleted
          // 更新当前消息列表，从头部插入
          // state.currentMessageList = mergeArray(currentMessageList, imReponse.data.messageList, 'ID')
          // 加载的新消息在后面
          state.currentMessageList = [...currentMessageList, ...imReponse.data.messageList]
          commit('set_currentMessageList', state.currentMessageList)
        }).catch(e => {
          console.error('   window.tim.getMessageList({', e)
        })
    },
    /**
     * 切换会话
     * 调用时机：切换会话时
     * 主要去获取messageList 通话过的消息
     * @param {Object} context
     * @param {String} conversationID
     */
    action_checkoutConversation ({ state, commit, dispatch }, currentConversation) {
      // 1.切换会话前，将切换前的会话进行已读上报
      if (state.currentConversation.conversationID) {
        const prevConversationID = state.currentConversation.conversationID
        window.tim.setMessageRead({ conversationID: prevConversationID })
      }
      // 2.待切换的会话也进行已读上报
      window.tim.setMessageRead({ conversationID: currentConversation.conversationID })
      // 3. 获取会话信息
      return window.tim.getConversationProfile(currentConversation.conversationID).then(({ data }) => {
        // 3.1 更新当前会话
        commit('checkoutConversation', data.conversation)
        // 3.2 获取消息列表
        dispatch('getMessageList', data.conversation)
        // // 3.3 拉取第一页群成员列表
        // if (data.conversation.type === TIM.TYPES.CONV_GROUP) {
        //   return context.dispatch('getGroupMemberList', data.conversation.groupProfile.groupID)
        // }
        return Promise.resolve()
      })
    },
    /* 创建一个组*/
    actions_createGroup ({ state }) {
      var getOptions = {
        groupID: 'group1',
        name: 'group1',
        type: window._vm.TIM.TYPES.GRP_CHATROOM,
        avatar: '',
        introduction: '',
        notification: '',
        joinOption: 'FreeAccess',
        memberList: ['user0', 'user1'],
      }
      window._vm.tim.createGroup(getOptions).then((imResponse) => {
      }).catch(e => {
        console.log('createGroup fail', e)
        throw e
      })
    }
  },
}
